import React, { useEffect, useMemo, useRef, useState } from 'react'
import { Button, Input,NavBar } from 'antd-mobile'
import { useNavigate, Outlet } from 'react-router-dom'
import styles from './ser.module.css'
function Index() {
    let navigate = useNavigate()
    const chatEl=useRef(null)
    const [msgVal,setMsgVal]=useState('')
    const [chatList,setChatList]=useState([])
    const user_id=1
    const server_id=4567
    const ws=useMemo(()=>{
     return new WebSocket(`
      ws:124.221.74.149:8003/koa/ws?user_id=${user_id}&server_id=${server_id}  `)   
    },[])
    useEffect(()=>{
        ws.onopen=()=>{
            console.log('链接成功');
            ws.send(JSON.stringify({type:'getChatList'}))
        }
        ws.onmessage=(msg)=>{
            console.log(msg);
            const{type,data}=JSON.parse(msg.data)
            console.log(data);
            if(type==='getChatList'){
                setChatList(data)
            }else if(type==='addMessage'){
                setChatList(pre=>[...pre,data])
            }
        }
    },[])
    const handelfs=()=>{
        ws.send(JSON.stringify({
            type:'addMessage',
            data:{
                user_id,
                server_id,
                message:msgVal
            }
        }))
      setMsgVal('')

    }
    useEffect(()=>{
        if(chatEl.current){
            chatEl.current.scrollTop=10000
        }
    },[chatList])
  return (
    <div className={styles.serBox}>
        <NavBar onBack={()=>navigate(-1)}>小白</NavBar>
      <main ref={chatEl}>
        <div>
            {
                chatList.length>0 && chatList.map((item,ind)=>{
                    const classitem=
                    item.dir==1
                    ?'seat-item-r'
                    :'seat-item-l'
                    const diravatar=
                    item.dir==1
                    ?item.user_avatar
                    :item.server_avatar

                    return(
                        <div className={styles[classitem]}>
                            <img src={diravatar} alt="" width={50} height={50} style={{borderRadius:'50%'}} />
                            <div className={styles.text}>{item.message}</div>
                        </div>
                    )
                })
            }
        </div>
      </main>
      <footer>
         <Input
          placeholder='请输入内容'
          value={msgVal}
          onChange={val => {
            setMsgVal(val)
          }}
        />
        <Button onClick={()=>handelfs()}>发送</Button>

      </footer>
    </div>
  )
}

export default Index
